package com.example.aop.cglib;

import java.lang.reflect.Method;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import com.example.aop.jdk.PerformanceMonitor;

public class CglibProxy implements MethodInterceptor {
    private Enhancer enhancer = new Enhancer();

    /**
     * 动态创建带有横切逻辑的代理实例
     * 
     * @param enhancer
     *            增强对象
     * @param method
     * @param args
     * @param methodProxy
     *            拦截目标对象类的所有方法的子类
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object enhancer, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        PerformanceMonitor.begin(enhancer.getClass().getName() + method.getName());
        Object obj = methodProxy.invokeSuper(enhancer, args);// 通过代理子类调用父类的方法
        PerformanceMonitor.end();
        return obj;
    }

    public Object getProxy(Class clazz) {
        enhancer.setSuperclass(clazz);// 目标对象类
        enhancer.setCallback(this);
        return enhancer.create();// 通过字节码技术创建目标对象类的子类实例作为代理
    }
}